package com.atguigu.msmservice.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.aliyuncs.CommonRequest;
import com.aliyuncs.CommonResponse;
import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.exceptions.ClientException;
import com.aliyuncs.exceptions.ServerException;
import com.aliyuncs.http.MethodType;
import com.aliyuncs.profile.DefaultProfile;
import com.atguigu.msmservice.service.MsmService;
import com.atguigu.msmservice.utils.MessagePropertiesUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Map;

@Service
public class MsmServiceImpl implements MsmService {


    /**
     * 根据手机号、短信模板id、短信模板变量对应的实际值发送短信验证码
     *
     * @param phone        手机号
     * @param templateCode 短信模板id
     * @param param        短信模板变量对应的实际值
     * @return
     */
    @Override
    public boolean sendMsm(String phone, String templateCode, Map<String, Object> param) {
        if (StringUtils.isEmpty(phone)) return false;
        DefaultProfile profile =
                DefaultProfile.getProfile(MessagePropertiesUtils.REGION_ID, MessagePropertiesUtils.ACCESS_KEY_ID, MessagePropertiesUtils.ACCESS_KEY_SECRET);
        IAcsClient client = new DefaultAcsClient(profile);
        CommonRequest request = new CommonRequest();
        //request.setProtocol(ProtocolType.HTTPS);
        request.setMethod(MethodType.POST);
        request.setDomain(MessagePropertiesUtils.MSM_URL); //请求阿里云短信服务的地址
        request.setVersion(MessagePropertiesUtils.VERSION); //版本号
        request.setAction(MessagePropertiesUtils.METHOD_NAME); //阿里云短信服务方法名
        request.putQueryParameter("PhoneNumbers", phone);
        request.putQueryParameter("SignName", "我的谷粒在线教育网站"); //短信签名名称
        request.putQueryParameter("TemplateCode", MessagePropertiesUtils.TEMPLATE_CODE); //短信模板id
        request.putQueryParameter("TemplateParam", JSONObject.toJSONString(param)); //短信模板code变量对应的实际值，JSON格式
        try {
            CommonResponse response = client.getCommonResponse(request);
            return response.getHttpResponse().isSuccess();
        } catch (ServerException e) {
            e.printStackTrace();
        } catch (ClientException e) {
            e.printStackTrace();
        }
        return false;
    }
}
